package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.server.pojo.TimeLine;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * * @title: TimeLineService
 *
 * @Author Philcan
 * @Date: 2021/8/11 21:06
 * @Version 1.0
 */
@Service
@Slf4j
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId) {
        try {
            Query query = Query.query(Criteria.where("userId").is(userId));
            List<Users> users = this.mongoTemplate.find(query, Users.class);
            if (CollUtil.isEmpty(users)) {
                return CompletableFuture.completedFuture("ok");
            }
            for (Users user : users) {
                TimeLine timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setDate(System.currentTimeMillis());
                timeLine.setPublishId(publishId);
                timeLine.setUserId(userId);
                this.mongoTemplate.save(timeLine, "quanzi_time_line_" + user.getFriendId());
            }
        } catch (Exception e) {
            log.error("写入好友时间线失败,userId="+userId+",publishId="+publishId,e);
            return CompletableFuture.completedFuture("error");
        }
        return CompletableFuture.completedFuture("ok");
    }
}
